package cn.com.jit;

import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class XmlFileProcessor implements FileProcessor {

    @Override
    public List<SqlVo> processFile(File file) {
        List<SqlVo> sqls = new ArrayList<>();
        try {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser saxParser = factory.newSAXParser();
            MySaxHandler handler = new MySaxHandler(sqls, file.getPath());
            saxParser.parse(file, handler);
        } catch (Exception e) {
            System.err.println("Error parsing XML file: " + file.getName() + " - " + e.getMessage());
        }
        return sqls;
    }

    static class MySaxHandler extends DefaultHandler {
        private List<SqlVo> sqls;
        private String filePath;
        private StringBuilder currentText = new StringBuilder();
        private boolean inSelect = false;
        private boolean inUpdate = false;
        private int lineNumber = -1;

        public MySaxHandler(List<SqlVo> sqls, String filePath) {
            this.sqls = sqls;
            this.filePath = filePath;
        }

        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
            lineNumber++;
            if (qName.equalsIgnoreCase("select")) {
                inSelect = true;
            } else if (qName.equalsIgnoreCase("update")) {
                inUpdate = true;
            }
        }

        @Override
        public void endElement(String uri, String localName, String qName) throws SAXException {
            if (inSelect || inUpdate) {
                String text = currentText.toString().trim();
                if (!text.isEmpty()) {
                    SqlVo sqlVo = new SqlVo(filePath, text,lineNumber);
                    sqls.add(sqlVo);
                }
                currentText = new StringBuilder();
                inSelect = false;
                inUpdate = false;
            }
        }

        @Override
        public void characters(char[] ch, int start, int length) throws SAXException {
            currentText.append(ch, start, length);
        }
    }
}
